package com.saber;

import com.rabbitmq.client.*;
import com.rabbitmq.client.Consumer;
import com.saber.util.RabbitmqUtil;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeoutException;

/**
 * Created by PC on 2017/10/18.
 */
public class ReceiveLogsDirect2 {

    // 路由关键字
    private static final String[] routingKeys = new String[]{"error"};

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitmqUtil.buildConnection();
        Channel channel = connection.createChannel();

        //声明交换器
        channel.exchangeDeclare(RoutingSendDirect.EXCHANGE_NAME,"direct");

        //获取匿名队列名称
        String queueName = channel.queueDeclare().getQueue();

        //绑定
        for (String routingKey : routingKeys) {
            channel.queueBind(queueName,RoutingSendDirect.EXCHANGE_NAME,routingKey);
            System.out.println("ReceiveLogsDirect2 exchange:" + RoutingSendDirect.EXCHANGE_NAME + ", queue:" + queueName + ", BindRoutingKey:" + routingKey);
        }

        System.out.println("ReceiveLogsDirect2 Waiting for messages");

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws UnsupportedEncodingException {
                String message = new String(body, "UTF-8");
                System.out.println("ReceiveLogsDirect2 Received '" + envelope.getRoutingKey() + "':'" + message + "'");
            }
        };
        channel.basicConsume(queueName, true, consumer);
    }
}
